package com.logistics.user;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.ResultSet;
import java.sql.SQLException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.logistics.database.Userdatabase;

public class Logincheckservlet extends HttpServlet {
	Userdatabase udb;
	/**
	 * Constructor of the object.
	 */
	public Logincheckservlet() {
		super();
	}

	/**
	 * Destruction of the servlet. <br>
	 */
	public void destroy() {
		super.destroy(); // Just puts "destroy" string in log
		// Put your code here
	}

	/**
	 * The doGet method of the servlet. <br>
	 *
	 * This method is called when a form has its tag value method equals to get.
	 * 
	 * @param request the request send by the client to the server
	 * @param response the response send by the server to the client
	 * @throws ServletException if an error occurred
	 * @throws IOException if an error occurred
	 */
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		String username=new String(request.getParameter("userEntity.userCode").getBytes("iso-8859-1"),"utf-8");
		String password=new String(request.getParameter("userEntity.password").getBytes("iso-8859-1"),"utf-8");
		System.out.println("username="+username+" password="+password);
		
		ResultSet rs=udb.userQuery(username,password);
		int authority=-1;
		try {
			if(rs.next())
			{
				
				authority=rs.getInt("authority");
				HttpSession session =request.getSession();
				session.setAttribute("authority", authority);
				session.setAttribute("user_name", username);
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		if(authority==-1)
		{
			response.sendRedirect("../login.jsp");
			//request.getRequestDispatcher("../login.jsp").forward(request, response);
		}
		else
		{
			response.sendRedirect("../main/main.jsp");
			//request.getRequestDispatcher("../main/main.jsp").forward(request, response);
		}
		
	}

	/**
	 * The doPost method of the servlet. <br>
	 *
	 * This method is called when a form has its tag value method equals to post.
	 * 
	 * @param request the request send by the client to the server
	 * @param response the response send by the server to the client
	 * @throws ServletException if an error occurred
	 * @throws IOException if an error occurred
	 */
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		doGet(request,response);
	}

	/**
	 * Initialization of the servlet. <br>
	 *
	 * @throws ServletException if an error occurs
	 */
	public void init() throws ServletException {
		// Put your code here
		udb=new Userdatabase();
	}

}
